package com.pai4j.ugc.service.moment;

import com.pai4j.common.bean.PAIPageResponseBeanUtil;
import com.pai4j.domain.vo.response.moment.MomentVO;
import com.pai4j.ugc.repository.dao.IMomentAiKeywordDAO;
import com.pai4j.ugc.repository.entity.MomentAiKeywordEntity;
import com.pai4j.ugc.repository.dao.custom.MomentKeywordQueryRepository;
import jakarta.annotation.Resource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class MomentKeywordSearchService {

    @Resource
    private IMomentAiKeywordDAO momentAiKeywordDAO;
    @Resource
    private MomentKeywordQueryRepository keywordQueryRepository;

    @Resource
    private MomentService momentService;

    public PAIPageResponseBeanUtil<List<MomentVO>> searchByKeyword(String keyword, Integer pageNo, Integer pageSize) {
        return searchByKeywords(List.of(keyword), "time_desc", pageNo, pageSize);
    }

    /**
     * 多关键词检索，支持AND/OR，支持排序
     * sort:
     *  - time_desc / time_asc 按发布时间
     *  - score_desc / score_asc 按质量分
     */
    public PAIPageResponseBeanUtil<List<MomentVO>> searchByKeywords(List<String> keywords, String sort,
                                                                    Integer pageNo, Integer pageSize) {
        return searchByKeywordsWithMode(keywords, "AND", sort, pageNo, pageSize);
    }

    public PAIPageResponseBeanUtil<List<MomentVO>> searchByKeywordsWithMode(List<String> keywords, String mode, String sort,
                                                                            Integer pageNo, Integer pageSize) {
        int p = pageNo == null || pageNo < 1 ? 1 : pageNo;
        int s = pageSize == null || pageSize < 1 ? 10 : pageSize;

        // 数据库侧严格 AND/OR/NOT 分页 + 排序
        MomentKeywordQueryRepository.Result rs = keywordQueryRepository.queryByKeywords(
                keywords == null ? List.of() : keywords, mode, sort, p, s);
        List<MomentVO> moments = momentService.batchGetMomentFromCache(rs.momentIds());
        return PAIPageResponseBeanUtil.success(p, s, rs.total(), moments);
    }

    private int nvl(Integer v) { return v == null ? 0 : v; }
}

